<template>
    <TCollapse title="项目附件信息">
        <div ref="attachmentListRef" class="attachmentList">
            <MyTable
                id="fileId"
                ref="myTableRef"
                :is-mar-class="true"
                :table-data="tableData"
                :columns="columnEnum"
                :table-operation="btnEnum"
                :col-option-enum="dicLists"
                @propClick="btnClick"
            >
                <template #docTypeName="{ scope }">
                    <span v-if="+scope.isMust === 1" style="color: red">*</span>
                    <span>{{ scope.docTypeName }}</span>
                </template>
                <template #fileName="{ scope }">
                    <el-button type="text" @click="preview(scope)">
                        {{ scope.fileName }}
                    </el-button>
                </template>
            </MyTable>
            <pagination
                v-if="pageParam.total > 10"
                :total="pageParam.total"
                :page.sync="pageParam.pageNum"
                :limit.sync="pageParam.pageSize"
                @pagination="doSearch"
            />
            <!-- 上传附件 -->
            <el-dialog
                v-if="dialogUpload"
                ref="dialogUploadNewRef"
                v-dialogDrag
                :append-to-body="true"
                :modal-append-to-body="true"
                :close-on-click-modal="false"
                :modal="true"
                title="上传附件"
                width="50%"
                class="pms-zr-dialog"
                :visible.sync="dialogUpload"
                @close="() => { dialogUploadClosed() }"
            >
                <div style="max-height: 620px;overflow-y: auto;overflow-x: hidden;border: 1px solid #aaa;">
                    <UploadAttach
                        ref="uploadAttachRef"
                        :prj-params="prjParams"
                        :showSelect="false"
                        :prj-file-type-option="prjFileTypeOption"
                    />
                </div>
                <div slot="footer" class="pms-zr-dialog-footer">
                    <el-button class="pms-zr-button-primary" size="small" @click="startUpload">
                        开始上传
                    </el-button>
                    <el-button
                        class="pms-zr-button-primary pms-zr-ClosedBtn"
                        size="small"
                        @click="() => { dialogUploadClosed() }"
                    >
                        关 闭
                    </el-button>
                </div>
            </el-dialog>
            <!-- 文件预览 -->
            <el-dialog
                v-if="dialogFileView"
                ref="dialogViewRef"
                v-dialogDrag
                :append-to-body="true"
                :modal-append-to-body="true"
                :modal="true"
                :close-on-click-modal="false"
                :lock-scroll="true"
                title="预览"
                height="60%"
                width="60%"
                class="pms-zr-dialog"
                :visible.sync="dialogFileView"
                @close="() => { dialogUploadClosed() }"
            >
                <div class="signatoryPre">
                    <FilePreview ref="filePreviewRef" class="filePreviewClass" :file-obj="fileObj" />
                </div>
                <div slot="footer" class="pms-zr-dialog-footer">
                    <el-button
                        class="pms-zr-button-primary"
                        style="background-color: #eb4b4b; color: #fff;"
                        size="small"
                        @click="() => { dialogFileView = false; }"
                    >
                        取 消
                    </el-button>
                </div>
            </el-dialog>
        </div>
    </TCollapse>
</template>

<script>
import { getDropdownData } from '@/api/common' // 字典接口
import FilePreview from "@/components/business/filePreview.vue";
import UploadAttach from "@/components/attachmentInfo/uploadAttach.vue";
import MyTable from "@/components/basic/myTable.vue";
import SysConst from '@/common/const'
import {disableScroll, downloadFileFun, enableScroll, msgInfoEl} from "@/utils";
import {
    batchDeleteApi,
    getPreviewFile,
    getPrjStageApi,
    getWPSToken,
    getPrjFileTypeApi,
    queryDocInfo, batchDownloadApi, downloadApi, querySuffix,
} from "@/api/attachmentInfo";

export default {
    name: 'AttachmentInfo',
    components: { MyTable, UploadAttach, FilePreview},
    props: {
        prjParams: {
            type: Object,
            default: () => ({})
        }
    },
    data(){
        return {
            tableData: [], // 附件列表数据
            prjFileTypeOption:[],
            columnEnum:[
                { label: '项目阶段', width: '120', prop: 'prjStage', dicType: 'PRO_STAGE', dicProp: { label: 'dictName', value: 'dictId' }},
                { label: '项目节点', width: '120', prop: 'nodeName' },
                { label: '文件类型', width: '180', prop: 'docTypeName' },
                { label: '文件名称', width: '', prop: 'fileName' },
                { label: '上传人', width: '120', prop: 'uploaderName' },
                { label: '上传时间', width: '160', prop: 'uploadTime' },
                { label: '文件获取方式', width: '140', prop: 'fileSource', filter: { '0': '手动上传', '1': '系统生成', '2': '系统生成/手动编辑', '3': '电子文档' }}, // 0-手动上传，1-系统生成，2-系统生成/手动编辑
                { label: '是否必传', width: '100', prop: 'isMust', filter: { '1': '必传', '0': '非必传' }}],
            btnEnum:[],
            dicLists:{},
            dialogUpload:false,
            dialogFileView:false,
            // 分页信息
            pageParam: {
                pageSize: SysConst.PAGESIZE, // 每页显示val条
                pageNum: SysConst.CURRENT_PAGE, // 当前页
                total: SysConst.TOTAL // 总数
            },
            wpsToken:'',
            previewObj:{},
        }
    },
    async created(){
        console.log(this.$route.query.type)
        if(this.$route.query.type === 'todo'){
            this.getPrjFileType()
            this.btnEnum=[
                { label: '上传附件', fun: 'upload', type: '' },
                { label: '删除附件', fun: 'delete', type: '' },
                { label: '下载附件', fun: 'download', type: '' }
            ]
        }else{
            this.btnEnum=[
                { label: '下载附件', fun: 'download', type: '' }
            ]
        }
        await this.getDictData()
        await this.getPrjStage()
        await this.getToken()
        await this.querySuffix()
        await this.doSearch()
    },
    methods:{
        querySuffix() {
            querySuffix().then((res) => {
                if (+res.code === 200) {
                    this.previewObj = res.data
                }
            })
        },
        getToken() {
            getWPSToken().then((res) => {
                if (+res.code === 200) {
                    this.wpsToken = res.data
                }
            })
        },
        // 查看数据
        doSearch(item) {
            let params = {
                prjId: this.prjParams.prjId,
                prjStage: this.prjParams.prjStage,
                nodeId: this.prjParams.nodeId,
                flagNum: '1',
                prjCode: '',
                prjType: this.prjParams.prjType,
                processId: this.prjParams.processId,
                isWaitFlag: '',
                pageNum: item?.page || SysConst.CURRENT_PAGE,
                pageSize: item?.limit || SysConst.PAGESIZE,
            }
            queryDocInfo(params).then(res => {
                if (+res.code !== 200) {
                    return Promise.reject(res)
                }
                console.log(res, '附件信息')
                this.tableData = res.data.records
                this.pageParam.total = res.data?.total || 0
                this.pageParam.pageSize = item?.limit || SysConst.PAGESIZE
                this.pageParam.pageNum = item?.page || SysConst.CURRENT_PAGE
            })
        },
        // 获取附件允许上传文件类型数据
        getPrjFileType() {
            const {
                prjType, // 项目类型
                nodeId, // 当前节点ID
                buildModes, // 建设模式
                towerType, // 塔类型
                orgId,
                roomType // 室分类型
            } = this.prjParams
            const params = {
                prjType, // 项目类型
                nodeId, // 当前节点ID
                buildModes, // 建设模式
                towerType, // 塔类型
                roomType, // 室分类型
                orgId,
                businessMajor: '',
                businessType: '',
            }
            getPrjFileTypeApi(params).then(res => {
                if (+res.code !== 200) {
                    return Promise.reject(res)
                }
                this.prjFileTypeOption = res.data
            })
        },
        // 获取下拉框字典数据
        async getDictData() {
            const arr = ['SIGN_STATE2']
            const promises = arr.map(item => getDropdownData(item))
            const results = await Promise.all(promises)
            arr.forEach((item, i) => {
                this.$set(this.dicLists, item, results[i].data ?? [])
            })
        },
        // 获取项目阶段字典
        async getPrjStage() {
            const res = await getPrjStageApi()
            const stageData = res.data.map(item => ({
                dictId: item.key,
                dictName: item.value
            }))
            this.$set(this.dicLists, 'PRO_STAGE', stageData)
        },
        btnClick(fun, row) {
            this[fun](row)
        },
        dialogUploadClosed(){
            this.dialogUpload = false
            this.dialogFileView=false
            this.doSearch()
        },
        startUpload(){
            this.$refs.uploadAttachRef.startUpload()
        },
        upload(){
            if (this.prjFileTypeOption.length > 0) {
                this.dialogUpload = true
            } else {
                msgInfoEl({
                    type: 'info',
                    message: '当前流程节点无可上传的附件信息，请联系维护人员增加上传需求'
                })
            }
        },
        // 删除附件按钮  代码合并后 增加nodeId
        delete(row) {
            const isRel = row.some(item => item.fileSource !== '0')
            if (isRel) {
                return msgInfoEl({
                    type: 'info',
                    message: '仅支持文件获取方式为手动上传的文件'
                })
            }
            const isRemove = row.some(item => item.nodeId !== row[0].nodeId)
            if (isRemove) {
                return msgInfoEl({
                    type: 'info',
                    message: '不同节点不支持批量删除'
                })
            }
            const params = [];
            row.forEach((item)=>{
                if(item.fileId){
                    params.push({
                        fileId:item.fileId,
                        prjId:item.prjId,
                        supplementType:this.$route.meta.supplementType,
                        nodeId: this.prjParams.nodeId,
                    })
                }
            })
            if(params.length > 0){
                this.deleteConfirm(params);
            }else{
                return msgInfoEl({
                    type: 'error',
                    message: '没有文件可进行删除'
                })
            }
        },
        deleteConfirm(params){
            const contentBody = window.top.document.body
            this.$confirm('确认删除所选数据, 是否继续?', '删除', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                cancelButtonClass: 'pms-zr-button',
                confirmButtonClass: 'pms-zr-button-primary',
                closeOnClickModal: false
            }).then(() => {
                batchDeleteApi(params).then(res => {
                    if (+res.code !== 200) {
                        return Promise.reject(res)
                    }
                    this.doSearch({
                        page: this.pageParam.pageNum,
                        limit: this.pageParam.pageSize
                    })
                    this.$refs.myTableRef.clearSelection()
                    // this.$refs.myTableRef.toggleRowSelection(row)
                    enableScroll(contentBody)
                    msgInfoEl({
                        type: 'success',
                        message: res.message
                    })
                })
            }).catch(() => {
                enableScroll(contentBody)
                console.log('取消删除了')
            })
            // el-message-box__wrapper
            // 将弹框挂载在最外层
            this.$nextTick(() => {
                const msgBox = document.querySelector('.el-message-box__wrapper')
                contentBody.appendChild(msgBox)
                disableScroll(contentBody)
            })
        },
        getUserId(){
            let str='';
            if(sessionStorage.getItem('SET_LOGINDATA')){
                str = JSON.parse(sessionStorage.getItem('SET_LOGINDATA')).staffId
            }else if(sessionStorage.getItem('userInfo')){
                str = JSON.parse(sessionStorage.getItem('userInfo')).staffId
            }else{
                console.log('')
            }
            console.log('str',str)
            return str;
        },
        // 点击文件名称-预览
        async preview(row) {
            const types = row.fileName.substring(row.fileName.lastIndexOf('.') + 1)
            const previewArray = Object.keys(this.previewObj);
            console.log(111,previewArray,this.previewObj,this.previewObj[types])
            if (previewArray.includes(types)) {
                const params = {
                    fileId: row.fileId,
                    type: this.previewObj[types],
                    userId: this.getUserId(),
                    token: this.wpsToken
                }
                getPreviewFile(params).then((res) => {
                    if (+res.code === 200 && res.data) {
                        window.open(res.data, '_blank')
                    }
                })
            } else {
                return msgInfoEl({
                    type: 'info',
                    message: `所选文件不支持预览`
                })
            }
        },
        // 下载
        download(row) {
            console.log(row, '下载--row')
            const fileDownloadNo = row.find(item => item.fileId === '' || item.fileId === null || item.fileId === undefined) || {}
            if (JSON.stringify(fileDownloadNo) !== '{}') {
                return msgInfoEl({
                    type: 'info',
                    message: `当前选择范围中存在未上传文件，请上传或取消勾选该文件再进行下载`
                })
            }
            const fileName = row.length > 1 ? '附件信息.zip' : row[0].fileName
            // 单个文件下载时的参数
            const params = {
                fileId: row[0].fileId,
                fileName: row[0].fileName
            }
            // 多个文件下载时的参数
            const batchParams = row.map(item => ({
                fileId: item.fileId,
                fileName: item.fileName
            }))
            if (row.length > 1) {
                // mulDownload(row, fileName)
                // 批量下载
                batchDownloadApi({ fileMap: batchParams }).then(res => {
                    console.log(res, '下载')
                    downloadFileFun(res, fileName)
                })
            } else {
                // singleDownload(row, fileName)
                // 单个文件下载
                downloadApi(params).then(res => {
                    console.log(res, '下载')
                    downloadFileFun(res, fileName)
                })
            }
        },
    }
}
</script>

<style scoped lang="scss">
.el-button--text {
    color: #02A7F0;
}
</style>